<template>
  <div>
    <el-form :inline="true" :model="dataForm" :rules="dataRule" ref="dataForm" class="form">
      <el-form-item prop="name">
        <el-select
            v-model="dataForm.name"
            class="input"
            placeholder="选择会议室"
            size="medium"
            clearable="clearable"
        >
          <el-option v-for="one in roomList" :label="one.name" :value="one.name"/>
        </el-select>
      </el-form-item>
      <el-form-item prop="date">
        <el-date-picker
            v-model="dataForm.date"
            type="date"
            placeholder="选择日期"
            class="input"
            size="medium"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button size="medium" type="primary" @click="searchHandle()">查询</el-button>
        <el-button size="medium" type="danger" @click="addHandle()">会议申请</el-button>
      </el-form-item>
      <el-form-item class="mold">
        <el-radio-group v-model="dataForm.mold" size="medium" @change="changeHandle">
          <el-radio-button label="全部会议"></el-radio-button>
          <el-radio-button label="我的会议"></el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <div class="gantt"
         ref="gantt"
         v-show="mode == 'gantt'"
    >
      <div class="row">
        <div class="cell-time"></div>
        <div class="cell-time" v-for="one in time">
          <span class="time">{{ one }}</span>
        </div>
      </div>
      <div class="row" v-for="room in gantt.meetingRoom">
        <div class="cell room">{{ room.name }}</div>
        <div class="cell" v-for="one in time">
          <div
              v-if="room.meeting.hasOwnProperty(one)"
              class="meeting"
              :class="room.meeting[one].split('#')[1]"
              :style="'width:' + room.meeting[one].split('#')[0] * gantt.cellWidth + 'px'"
          ></div>
        </div>
      </div>
    </div>

    <el-pagination
        v-show="mode == 'gantt'"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
    />

    <div class="calendar" v-show="mode == 'calendar'">
      <div class="row">
        <div class="cell">时间</div>
        <div class="cell" v-for="one in calendar.days">{{ one.date }}（{{ one.day }}）</div>
      </div>
      <div class="row" v-for="(one, index) in time">
        <div class="cell-time" v-if="time[index + 1] != null">{{ one }} ~ {{ time[index + 1] }}</div>
        <div class="cell" v-for="day in calendar.days" v-if="time[index + 1] != null">
          <div
              class="meeting"
              v-if="calendar.map.hasOwnProperty(`${day.date}#${one}`)"
              :style="
							'height:' + calendar.map[day.date + '#' + one].time * 31 + 'px;' +
							'line-height:' + calendar.map[day.date + '#' + one].time * 31 + 'px'
            "
              :ref="`${day.date}#${one}`"
              @click="infoHandle(calendar.map[day.date + '#' + one].id, calendar.map[day.date + '#' + one].status)"
          >
            <SvgIcon
                name="close"
                class="icon-svg-close"
                v-if="
									calendar.map[`${day.date}#${one}`].isCreator == 'true' &&
									[1, 3].includes(calendar.map[`${day.date}#${one}`].status)
								"
                @click.stop="deleteHandle(`${day.date}#${one}`)"
            />
            {{ calendar.map[`${day.date}#${one}`].title }}
          </div>
        </div>
      </div>
    </div>
    <add v-if="addVisible" ref="add" @refresh="refresh"></add>
    <info v-if="infoVisible" ref="info"></info>
  </div>
</template>

<script>
import SvgIcon from '../../components/SvgIcon.vue';
import dayjs from 'dayjs';
import Add from './components/offline_meeting-add.vue';
import Info from './components/offline_meeting-info.vue';

export default {
  components: {SvgIcon, Add, Info},
  data: function () {
    return {
      time: [
        '08:30',
        '09:00',
        '09:30',
        '10:00',
        '10:30',
        '11:00',
        '11:30',
        '12:00',
        '12:30',
        '13:00',
        '13:30',
        '14:00',
        '14:30',
        '15:00',
        '15:30',
        '16:00',
        '16:30',
        '17:00',
        '17:30',
        '18:00',
        '18:30'
      ],
      // 甘特图的各种业务数据
      gantt: {
        meetingRoom: [],
        cellWidth: 0
      },
      // 周日历的各种业务数据
      calendar: {
        map: {},
        days: []
      },
      // 条件查询的会议室下拉列表数据
      roomList: [],
      dataForm: {
        name: null,
        date: null,
        mold: '全部会议'
      },
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      addVisible: false,
      infoVisible: false,
      dataRule: {},
      // 显示哪种界面（日程表或周日历）
      mode: 'gantt',
      auditMeeting: [],
      meeting: {
        end: "09:00",
        time: 1,
        start: "08:30",
        status: 1
      }
    };
  },
  methods: {
    // 加载会议数据
    loadDataList() {
      let _this = this;
      let data = {
        name: _this.dataForm.name,
        mold: _this.dataForm.mold,
        page: _this.pageIndex,
        length: _this.pageSize
      }

      if (_this.dataForm.date === null || _this.dataForm.date === '') {
        data.date = dayjs(new Date()).format("YYYY-MM-DD")
      } else {
        data.date = dayjs(_this.dataForm.date).format("YYYY-MM-DD")
      }
      console.log(data)
      _this.$http('meeting/searchOfflineMeetingByPage', 'POST', data, true, resp => {
        if (resp.code === 200) {
          let page = resp.page;
          let temp = []
          console.log(page.list)
          // 单条记录：name: '会议室B2', auditMeeting: '[{"end": "09:00", "time": 1, "start": "08:30", "status": 1}]
          for (let room of page.list) {
            let json = {}
            json.name = room.name
            json.meeting = {}
            // if 执行的次数正常
            if (room.hasOwnProperty('auditMeeting')) {
              // room数据也正常：{name: '会议室B2', auditMeeting: '[{"end": "09:00", "time": 1, "start": "08:30", "status": 1}]'}
              // auditMeeting数据：[{"end": "09:00", "time": 1, "start": "08:30", "status": 1}]
              this.auditMeeting = eval(room.auditMeeting);
              for (let auditMeeting of this.auditMeeting) {
                console.log(auditMeeting)
                let color = '';
                if (auditMeeting.status == 1) {
                  color = 'yellow'
                } else if (auditMeeting.status == 3) {
                  color = 'blue'
                } else if (auditMeeting.status == 4) {
                  color = 'pink'
                } else if (auditMeeting.status == 5) {
                  color = 'gray'
                }
                json.meeting[auditMeeting.start] = auditMeeting.time + "#" + color;
                console.log(json.meeting)
              }
            }
            temp.push(json);
          }
          console.log(temp)
          _this.gantt.meetingRoom = temp;
          _this.totalCount = page.totalCount;
        }
      })

    },
    backHandle: function () {
      let that = this;
      that.mode = 'gantt';
    },
    // 查询会议
    searchHandle() {
      let _this = this;
      // 查询甘特图的会议数据
      if (_this.dataForm.name === null || _this.dataForm.name === '') {
        _this.$refs['dataForm'].validate(valid => {
          if (valid) {
            _this.$refs['dataForm'].clearValidate();
            if (_this.pageIndex !== 1) {
              _this.pageIndex = 1;
            }
            _this.loadDataList();
            _this.mode = 'gantt';
          } else {
            return false;
          }
        })
      } else {
        // 查询周日历数据
        _this.$refs['dataForm'].validate(valid => {
          if (valid) {
            const loading = _this.$loading({
              lock: true,
              text: '正在加载',
              springgreen: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.5)'
            });
            _this.$refs['dataForm'].clearValidate();
            let data = {
              name: _this.dataForm.name,
              mold: _this.dataForm.mold
            }
            // 日历控件的值默认为null，有具体日期的日历被清除日期之后，值为空字符串
            if (_this.dataForm.date != null && _this.dataForm.date != '') {
              data.date = dayjs(_this.dataForm.date).format('YYYY-MM-DD');
            }
            _this.$http('meeting/searchOfflineMeetingInWeek', 'POST', data, true, resp => {
              let map = {};
              if (resp.code === 200) {
                loading.close();
                // 视图层输出会议卡片做判断遍历数组太麻烦，所以把周日历数据从数组转换成JSON对象
                for (const item of resp.list) {
                  map[`${item.date}#${item.start}`] = item;
                }
                _this.calendar.map = map;
                _this.calendar.days = resp.days;
                _this.mode = 'calendar';
              }
            })
          }
        })
      }
    },
    // 切换会议
    changeHandle() {
      this.searchHandle();
    },
    sizeChangeHandle(val) {
      this.pageIndex = val;
      this.pageIndex = 1;
      this.loadDataList();
    },
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.loadDataList();
    },
    // 打开会议申请dialog
    addHandle() {
      this.addVisible = true;
      this.$nextTick(() => {
        this.$refs.add.init();
      })
    },
    // 接受offline_meeting-add子组件传递的函数， 实现刷新最新数据
    refresh() {
      this.mode = 'gantt';
      this.$refs['dateForm'].resetFields();// 清空表单数据
      this.loadDataList();
    },
    // 点击会议详情
    infoHandle(id, status) {
      this.infoVisible = true;
      this.$nextTick(() => {
        this.$refs.info.init(id, status);
      })
    },
    // 删除会议
    deleteHandle(key) {
      this.$confirm('是否删除会议', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let loading = this.$loading({
          lock: true,
          text: '正在删除,请稍后',
          springgreen: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.5)'
        });
        let json = this.calendar.map[key];
        let data = {
          id: json.id,
          uuid: json.uuid,
          instanceId: json.instanceId,
          reason: '删除会议'
        }

        this.$http('meeting/deleteMeetingApplication', 'DELETE', data, true, resp => {
          if (resp.rows === 1) {
            loading.close();
            this.$message({
              message: "删除会议成功",
              type: 'success',
              duration: 1500
            })
            this.searchHandle();
          } else {
            loading.close();
            this.$message({
              message: "删除会议失败",
              type: 'error',
              duration: 1000
            })
          }
        })
      })
    }
  },
  mounted() {
    let that = this
    if (this.mode === 'gantt') {
      //根据实际情况设置甘特图每个单元格应该有的宽度
      let rowWidth = that.$refs['gantt'].cellWidth - 1;
      let cellWidth = rowWidth * 0.042 + 0.01;
      that.gantt.cellWidth = cellWidth;

      //当浏览器窗口尺寸改变的时候，重新设置甘特图单元格的宽度
      window.addEventListener('resize', () => {
        let rowWidth = that.$refs['gantt'].cellWidth - 1;
        let cellWidth = rowWidth * 0.042 + 0.01;
        that.gantt.cellWidth = cellWidth;
      })
    }
  },
  created: function () {

    let that = this;
    //加载会议室列表
    that.$http('meeting_room/searchAllMeetingRoom', 'GET', null, true, function (resp) {
      that.roomList = resp.list;
    });

    //加载分页数据
    that.loadDataList();
  },
};
</script>

<style lang="less" scoped="scoped">
@import url('../../style/offline_meeting.less');
</style>
